﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TekaMUD.Engine.Blocks;
using TekaMUD.Engine.Behaviour;
using TekaMUD.Engine.Framework;

namespace TekaMUD.Engine.ServerTasks
{
	/// <summary>
	/// Refreshes all NPC's in game.
	/// </summary>
	public class RefreshNPCTask : Task, IRepeatableTask
	{
		private const int FREQUENCY_SECONDS = 30;
		private TimeSpan period;

		public RefreshNPCTask() : base("Refresh NPC's")
		{
			period = new TimeSpan(0, 0, FREQUENCY_SECONDS);
		}

		// Only fast locks.
		public override void Execute()
		{
			// Iterate over all NPC's registered in the EntityManager.

			NPC[] targets = EntityManager.GetAllNPCs();

			if (targets == null)
				return;

			foreach (NPC target in targets)
			{
				if (target.ControlMutex.WaitOne(10))
				{
					IaEngine.Update(target);

					target.ControlMutex.ReleaseMutex();
				}
				else
				{
					Logger.LogDebug("Unable to acquire control of NPC " + target.UID);
				}
			}
		}

		public RepeatableTaskType RepeatType
		{
			get 
			{
				return RepeatableTaskType.Interval;
			}
		}

		public TimeSpan GetNextRunInterval()
		{
			return period;
		}

		public DateTime GetNextRunDate()
		{
			throw new InvalidOperationException();
		}
	}
}